﻿using Admin.NET.Application.Const;
using Admin.NET.Application.Entity;
using Admin.NET.Application.ServiceApi;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using Org.BouncyCastle.Ocsp;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Admin.NET.Application;
/// <summary>
/// 案例服务
/// </summary>
[AllowAnonymous]
[ApiDescriptionSettings(ApplicationConst.GroupNameApi, Order = 100)]
public class car_caseServiceApi : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<car_case> _rep;
    public car_caseServiceApi(SqlSugarRepository<car_case> rep)
    {
        _rep = rep;
    }



    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public async Task<SqlSugarPagedList<car_caseOutput>> Page(car_caseInputEx input)
    {
        //_rep.Context.Queryable<car_case, car_tagmap, car_tag>((c, tm, t) =>
        //        new JoinQueryInfos(
        //            JoinType.Inner, c.Id == tm.caseid,
        //            JoinType.Inner, tm.tagid == t.Id
        //        ))
        //    .Where((c, tm, t) => SqlFunc.ToLower(t.title).Contains(input.searchWork.ToLower().Trim()) )
        //    .Select(c => c)
        //    .Distinct()
        //    .ToList();

        #region 1
        List<long> taglist = new List<long>();
        List<long?> mapIds = new List<long?>();
        if (!string.IsNullOrWhiteSpace(input.searchWork))
        {
            taglist = _rep.Context.Queryable<car_tag>().Where(m => SqlFunc.ToLower(m.title).Contains(input.searchWork.ToLower().Trim())).Select(m => m.Id).ToList();
            // 第二步：查询CaseIds
              mapIds = _rep.Context.Queryable<car_tagmap>()
                .Where(tm => taglist.Contains(tm.tagid))
                .Select(tm => tm.caseid)
                .Distinct()
                .ToList();

        }
        var query = _rep.AsQueryable().Where(m => m.IsDelete == false)
           //.LeftJoin<car_tagmap>((m, tm) => m.Id == tm.caseid)
           // .LeftJoin<car_tag>((m, tm, tg) => tm.tagid ==tg.Id)
           .Includes(m => m.tags)
               .WhereIF(!string.IsNullOrWhiteSpace(input.title), u => u.title.Contains(input.title.Trim()))
               .WhereIF(input.carid > 0, m => m.tags.Count(t => t.tagid == input.carid) > 0)
               .WhereIF(input.colorId > 0, m => m.tags.Count(t => t.tagid == input.colorId) > 0)
               .WhereIF(input.zhiganId > 0, m => m.tags.Count(t => t.tagid == input.zhiganId) > 0)
               .WhereIF(input.xilieId > 0, m => m.tags.Count(t => t.tagid == input.xilieId) > 0)
               .WhereIF(input.xilieSubId > 0, m => m.tags.Count(t => t.tagid == input.xilieSubId) > 0)
               .WhereIF(input.sexiId > 0, m => m.tags.Count(t => t.tagid == input.sexiId) > 0)
               .WhereIF(!string.IsNullOrWhiteSpace(input.searchWork) && mapIds.Count == 0, u => u.title.Contains(input.searchWork.Trim()))
                //  .WhereIF(taglist.Count > 0, m => m.tags.Count(t => taglist.Contains(t.tagid)) > 0)
                .WhereIF(mapIds.Count > 0, m => mapIds.Contains(m.Id))

               .Select(u => new car_caseOutput
               {
                   Id = u.Id,
                   imageurls = u.imageurls,
                   coverurl = u.coverurl,
                   clickCount = u.clickCount,
                   tags = u.tags,
                   title = u.title,
                   //tag_car = u.tags.Where(tg => tg.tag.type == (int?)car_tagType.car).Select(m => m.tag).ToList(),
                   //tag_color = u.tags.Where(tg => tg.tag.type == (int?)car_tagType.color).Select(m => m.tag).ToList(),
                   //tag_sexi = u.tags.Where(tg => tg.tag.type == (int?)car_tagType.sexi).Select(m => m.tag).ToList(),
                   //tag_xilie = u.tags.Where(tg => tg.tag.type == (int?)car_tagType.xilie).Select(m => m.tag).ToList(),
                   //tag_zhigan = u.tags.Where(tg => tg.tag.type == (int?)car_tagType.zhigan).Select(m => m.tag).ToList(),

               });
        #endregion

       
        if (input.isRandom && string.IsNullOrWhiteSpace(input.searchWork))
        {
            //  db.Queryable<Student>().Take(10).OrderBy(st => SqlFunc.GetRandom()).ToList();
            query.OrderBy(st => SqlFunc.GetRandom());
        }
        else
        {
            query = query.OrderBuilder(input, "clickCount");
        }

        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加案例
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task Add(Addcar_caseInput input)
    {

        var entity = input.Adapt<car_case>();
        await _rep.InsertAsync(entity);
    }


    /// <summary>
    /// 删除案例
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(Deletecar_caseInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _rep.FakeDeleteAsync(entity);   //假删除
    }

    /// <summary>
    /// 更新案例
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task Update(Updatecar_caseInput input)
    {
        var entity = input.Adapt<car_case>();
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取案例
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<car_case> Get([FromQuery] QueryByIdcar_caseInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取案例列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<object> List([FromQuery] car_caseInput input)
    {
        var list = _rep.AsSugarClient().Queryable<car_case>()
            .WhereIF(input.carid != 0, m => m.carid == input.carid)
            .ToList();

        return new
        {
            coverurl= list.Where(x => x.coverurl !=null).First().coverurl,
            list = list.Select(m => m.imageurls)

        };
    }





}

